﻿using AutoMapper;
using CarAppDomain.CarParts.Entities;
using CarAppDomain.CarParts.IRepository;
using CarAppDomain.CarType.Entities;
using CarAppDomain.CarType.IRepository;
using CarAppDomain.CarType.IService;
using CarAppDto.CarParts.CarPartsDtos;
using CarAppDto.CarType.CarTypeDtos;
using CarAppDto.CarType.CarTypeVersionDtos;
using CarAppDto.Dtos;
using D.Util.UtilCache;
using D.UtilCore.Dtos;
using D.UtilCore.Utils;
using D.UtilSqlsugarOrm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace CarAppDomain.CarType.Service
{
    public class CarTypeVersionService : BaseService<CarTypeVersionEntity>,ICarTypeVersionService
    {
        private readonly IMapper _mapper;
        private readonly ICacheService _cache;
        private readonly ICarTypeVersionEntityRepository _repository;
        private readonly ICarPartsEntityRepository _repositoryCarParts;
        private readonly IBrandEntityRepository _repositorBrand;
        private readonly IVehicleSeriesEntityRepository _repositoryVehicleSeries;
        private readonly ICarTypeEntityRepository _repositoryCarType;

        /// <summary>
        /// 构造注入
        /// </summary>
        public CarTypeVersionService(IMapper mapper, ICacheService cache, ICarTypeVersionEntityRepository repository, ICarPartsEntityRepository repositoryCarParts
            , IBrandEntityRepository repositorBrand, IVehicleSeriesEntityRepository repositoryVehicleSeries, ICarTypeEntityRepository repositoryCarType)
        {
            // 用于base方法
            base._baseDal = repository;
            this._repository = repository;
            _repositoryCarParts = repositoryCarParts;
            _cache = cache;
            _mapper = mapper;
            _repositorBrand = repositorBrand;
            _repositoryVehicleSeries = repositoryVehicleSeries;
            _repositoryCarType = repositoryCarType;
        }

        #region 增删改查


        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> AddCarTypeVersionAsync(ReqAddCarTypeVersion reqModel)
        {
            var exists = await _repository.ExistsAsync(m => m.Code == reqModel.Code);
            if (exists)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "编号重复" };
            }
            if (!string.IsNullOrWhiteSpace(reqModel.BrandId))
            {
                exists = await _repositorBrand.ExistsAsync(m => m.Id == reqModel.BrandId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "品牌信息不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.VehicleSeriesId))
            {
                exists = await _repositoryVehicleSeries.ExistsAsync(m => m.Id == reqModel.VehicleSeriesId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "车系信息不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.CarTypeId))
            {
                exists = await _repositoryCarType.ExistsAsync(m => m.Id == reqModel.CarTypeId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "车型信息不存在" };
                }
            }
            var insertEntity = _mapper.Map<ReqAddCarTypeVersion,CarTypeVersionEntity>(reqModel);
            insertEntity.DeleteFlag = false;
            insertEntity.CreateTime = DateTime.Now;
            insertEntity.Id = Guid.NewGuid().ToString();
            List<CarPartsCarTypeVersionEntity> carPartsVehicleSeriesList = new List<CarPartsCarTypeVersionEntity>();
            foreach (CarPartsCarTypeVersion item in reqModel.CarPartsCarTypeVersionList)
            {
                var carParts = await _repositoryCarParts.GetModelAsync(m => m.Id == item.CarPartsId);
                if (carParts == null)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "配件ID不存在" };
                }
                else
                {
                    CarPartsCarTypeVersionEntity carPartsVehicleSeries = new CarPartsCarTypeVersionEntity();
                    carPartsVehicleSeries.CarPartsId = item.CarPartsId;
                    carPartsVehicleSeries.SerialNumber = item.SerialNumber;
                    carPartsVehicleSeries.State = item.State;
                    carPartsVehicleSeries.ReplacedCarPartsId = item.ReplacedCarPartsId;
                    carPartsVehicleSeriesList.Add(carPartsVehicleSeries);
                }
            }
            var dbres = await _repository.AddCarTypeVersionAsync(insertEntity, carPartsVehicleSeriesList);
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> DeleteCarTypeVersionAsync(List<string> ids)
        {
            var dbres = await _repository.DeleteAsync(m => ids.Contains(m.Id));
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> UpdateCarTypeVersionAsync(ReqUpdateCarTypeVersion reqModel)
        {

            var updateEntity = await _repository.GetModelAsync(m => m.Id == reqModel.Id);
            if (updateEntity == null)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "该信息不存在" };
            }
            var exists = await _repository.ExistsAsync(m => m.Code == reqModel.Code&&m.Id!=reqModel.Id);
            if (exists)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "编号重复" };
            }
            if (!string.IsNullOrWhiteSpace(reqModel.BrandId))
            {
                exists = await _repositorBrand.ExistsAsync(m => m.Id == reqModel.BrandId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "品牌信息不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.VehicleSeriesId))
            {
                exists = await _repositoryVehicleSeries.ExistsAsync(m => m.Id == reqModel.VehicleSeriesId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "车系信息不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.CarTypeId))
            {
                exists = await _repositoryCarType.ExistsAsync(m => m.Id == reqModel.CarTypeId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "车型信息不存在" };
                }
            }
            updateEntity.Code=reqModel.Code;
            updateEntity.BrandId=reqModel.BrandId;
            updateEntity.VehicleSeriesId=reqModel.VehicleSeriesId;
            updateEntity.CarTypeId=reqModel.CarTypeId;
            updateEntity.Version=reqModel.Version;
            updateEntity.SalesName=reqModel.SalesName;
            updateEntity.CustomFields1 = reqModel.CustomFields1;
            updateEntity.CustomFields2 = reqModel.CustomFields2;
            updateEntity.CustomFields3 = reqModel.CustomFields3;
            updateEntity.CustomFields4 = reqModel.CustomFields4;
            updateEntity.CustomFields5 = reqModel.CustomFields5;
            updateEntity.CustomFields6 = reqModel.CustomFields6;
            updateEntity.CustomFields7 = reqModel.CustomFields7;
            updateEntity.CustomFields8 = reqModel.CustomFields8;
            updateEntity.CustomFields9 = reqModel.CustomFields9;
            updateEntity.CustomFields10 = reqModel.CustomFields10;
            updateEntity.UpdateTime = DateTime.Now;
            updateEntity.UpdateUser = reqModel.UpdateUser;
            List<CarPartsCarTypeVersionEntity> carPartsVehicleSeriesList = new List<CarPartsCarTypeVersionEntity>();
            foreach (CarPartsCarTypeVersion item in reqModel.CarPartsCarTypeVersionList)
            {
                var carParts = await _repositoryCarParts.GetModelAsync(m => m.Id == item.CarPartsId);
                if (carParts == null)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "配件ID不存在" };
                }
                else
                {
                    CarPartsCarTypeVersionEntity carPartsVehicleSeries = new CarPartsCarTypeVersionEntity();
                    carPartsVehicleSeries.CarPartsId = item.CarPartsId;
                    carPartsVehicleSeries.SerialNumber = item.SerialNumber;
                    carPartsVehicleSeries.State = item.State;
                    carPartsVehicleSeries.ReplacedCarPartsId = item.ReplacedCarPartsId;
                    carPartsVehicleSeries.CarTypeVersionId = reqModel.Id;
                    carPartsVehicleSeriesList.Add(carPartsVehicleSeries);
                }
            }
            var dbres = await _repository.UpdatCarTypeVersionAsync(updateEntity, carPartsVehicleSeriesList);
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<RepCarTypeVersion>>> QueryCarTypeVersionListAsync(ReqQueryCarTypeVersionList reqModel)
        {
            Expression<Func<CarTypeVersionEntity, bool>> where = null;

            if (!string.IsNullOrWhiteSpace(reqModel.BrandId))
                where = where.And(m => m.BrandId == reqModel.BrandId);

            if (!string.IsNullOrWhiteSpace(reqModel.CarTypeId))
                where = where.And(m => m.CarTypeId == reqModel.CarTypeId);

            if (!string.IsNullOrWhiteSpace(reqModel.VehicleSeriesId))
                where = where.And(m => m.VehicleSeriesId == reqModel.VehicleSeriesId);

            if (!string.IsNullOrWhiteSpace(reqModel.Code))
                where = where.And(m => m.Code.Contains(reqModel.Code));

            var res = await _repository.GetListAsync(where);
            return res.GetResponse();
        }

        /// <summary>
        /// 获取用户分页
        /// </summary>
        /// <param name="reqQueryAdminPage"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageModel<RepCarTypeVersion>>> QueryCarTypeVersionPagesAsync(ReqQueryCarTypeVersionPage reqQueryPage)
        {
            Expression<Func<CarTypeVersionEntity, bool>> where = null;

            if (!string.IsNullOrWhiteSpace(reqQueryPage.BrandId))
                where = where.And(m => m.BrandId == reqQueryPage.BrandId);

            if (!string.IsNullOrWhiteSpace(reqQueryPage.CarTypeId))
                where = where.And(m => m.CarTypeId == reqQueryPage.CarTypeId);

            if (!string.IsNullOrWhiteSpace(reqQueryPage.VehicleSeriesId))
                where = where.And(m => m.VehicleSeriesId == reqQueryPage.VehicleSeriesId);

            if (!string.IsNullOrWhiteSpace(reqQueryPage.Code))
                where = where.And(m => m.Code.Contains(reqQueryPage.Code));

            Expression<Func<CarTypeVersionEntity, object>> order = null;
            bool orderByAsc = true;
            if (reqQueryPage.Sorts != null && reqQueryPage.Sorts?.Count != 0)
            {
                SortDto sortDtoFrist = reqQueryPage.Sorts.FirstOrDefault();
                string sortField = sortDtoFrist?.Field;
                string sortOrder = sortDtoFrist?.Sort;
                order = ExpressionUtil.GetOrderObjectExpression<CarTypeVersionEntity>(sortField, sortOrder, ref orderByAsc);
            }
            else
                order = m => m.CreateTime;
            var dbres = await _repository.GetOrderPagesAsync(reqQueryPage.PageSize, reqQueryPage.PageNo, where, order, orderByAsc);
            var res = new PageModel<RepCarTypeVersion>()
            {
                PageNo = dbres.PageNo,
                PageSize = dbres.PageSize,
                TotalCount = dbres.TotalCount,
                TotalPage = dbres.TotalPage,
                Data = dbres.Data
            };
            return res.GetResponse();
        }

        /// <summary>
        /// 查询单个
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult<RepCarTypeVersion>> GetCarTypeVersionAsync(string id)
        {
            var dbres = await _repository.GetModelAsync(m => m.Id == id);
            var res = _mapper.Map<CarTypeVersionEntity, RepCarTypeVersion>(dbres);
            var carTypeDbRes = await _repositoryCarParts.GetCarPartsCarTypeVersion(res.Id);
            res.CarPartsCarTypeVersionList = carTypeDbRes;
            return res.GetResponse();
        }

        #endregion
    }
}
